package com.common.myspring.util;

import com.common.myspring.core.proxy.CglibProxy;
import com.common.myspring.core.proxy.JdkProxy;
import com.common.myspring.core.proxy.enums.ProxyEnum;

/**
 * @title: AopUtil
 * @Author xu-xiang
 * @Date: 2023/8/30 16:42
 * @description: 动态代理类
 */
public class AopUtil {

    public static <T> T getProxyInstance(T object, ProxyEnum type) {
        if (type == ProxyEnum.JDK) {
            if (object.getClass().getInterfaces().length == 0) {
                throw new RuntimeException("jdkProxy must contains one interface at least"); //JDK代理至少有一个接口
            }
            return JdkProxy.createProxyObject(object);
        }

        if (type == ProxyEnum.Cglib) {
            if (object.getClass().isInterface()) {
                throw new RuntimeException("cglibProxy must be an instance, not a interface"); //Cglib只能代理实例,无法接口
            }
            return CglibProxy.createProxyObject(object);
        }

        return getProxyInstance(object);
    }

    public static <T> T getProxyInstance(T object) {
        if (object == null) {
            return null;
        }

        Class<?> clazz = object.getClass();
        Class<?>[] interfaces = clazz.getInterfaces();
        T proxyBean = null;
        if (interfaces.length > 0) {
            proxyBean = JdkProxy.createProxyObject(object);
        } else {
            proxyBean = CglibProxy.createProxyObject(object);
        }

        return proxyBean;
    }


}
